﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Model.EntityModel;
using DataAccess;
using CustomControls;
using System.Globalization;
using System.Collections.ObjectModel;


namespace Project
{
    /// <summary>
    /// Interaction logic for UpdateDirectActionContent.xaml
    /// </summary>
    public partial class UpdateDirectActionContent : UserControl
    {
        
        InterveningPolice official = new InterveningPolice();
        Person aggressor = new Person();
        Actor aggressorActor = new Actor();
        Person complainant = new Person();
        Actor complainantActor = new Actor();
        DirectAction directAction = new DirectAction();
        Complaint complaint = new Complaint();
        //Functionary functionary = new Functionary();
        Employee functionary = new Employee();
        String Hours;
        String Minutes;
        long idComplaint;
        long LastCiEmployee=-1;
        SearchFunctionary search;
        GrantDirectorPermissionWindows Director;

        public UpdateDirectActionContent(long id)
        {
            InitializeComponent();
            idComplaint = id;
            lblCaseNumber.Content = idComplaint;
            try
            {
                complaint = DataAccess.ComplaintDataAccess.GetComplaintById(idComplaint);
                lblCaseDate.Content = complaint.RegistrationDate;
                directAction = DataAccess.DirectActionDataAccess.GetDirectActionById(Convert.ToInt64(complaint.IdDirectAction));
                official = InterveningPoliceDataAccess.GetPoliceByCi(Convert.ToInt64(directAction.CIInterveningPolice));
                functionary = DataAccess.EmployeeDataAccess.GetEmployeeByCi(Convert.ToInt64(directAction.CIEmployee));
                aggressorActor = DataAccess.PersonAndActorDataAccess.GetActorByTypeAndComplaintId("Agresor", Convert.ToInt64(complaint.Id));
                complainantActor = DataAccess.PersonAndActorDataAccess.GetActorByTypeAndComplaintId("Denunciante", Convert.ToInt64(complaint.Id));
                aggressor = DataAccess.PersonAndActorDataAccess.GetPersonById(aggressorActor.IdPerson.ToString());
                complainant = DataAccess.PersonAndActorDataAccess.GetPersonById(complainantActor.IdPerson.ToString());
                FillInformation();
                SetRules();
            }
            catch
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("La denuncia no tiene accion directa", "Informacion", MessageBoxButton.OK, MessageBoxImage.Information);
                this.Loaded += KillApp;
            }
        }

        private void KillApp(object sender, RoutedEventArgs e)
        {
            UIWindowManager.CleanWindow(this);
        }

        void FillInformation()
        {
            FillOfficer();
            FillFact();
            FillEmployee();
            FillComplainant();
            FillAggressor();
        }

        void FillComplainant()
        {
            TxtBoxCiComplainant.Text = complainant.CiPassport.ToString();
            TxtBoxComplainantName.Text=complainant.Name;
            TxtBoxComplainantPN.Text = complainant.PaternalName;
            TxtBoxComplainantMN.Text = complainant.MaternalName;
            TxtBoxComplainantOccupation.Text = complainant.Ocupation;
            TxtBoxComplainantPhone.Text = complainant.Phone;
            TxtBoxComplainantBornPlace.Text = complainant.BornCity;
            TxtBoxComplainantAddress.Text = complainant.Address;
            TxtBoxComplainantZone.Text = complainant.Zone;
            comboBoxComplainantMaritalStatus.Text = complainant.CivilStatus;
            datePickerBirthDateCamplainant.SelectedDate = complainant.BirthDate;
        }

        void FillAggressor()
        {
            TxtBoxDenouncedCi.Text = aggressor.CiPassport.ToString();
            TxtBoxDenouncedName.Text = aggressor.Name;
            TxtBoxDenouncedPN.Text = aggressor.PaternalName;
            TxtBoxDenouncedMN.Text = aggressor.MaternalName;
            TxtBoxDenouncedOccupation.Text = aggressor.Ocupation;
            TxtBoxDenouncedPhone.Text = aggressor.Phone;
            TxtBoxDenouncedBornPlace.Text = aggressor.BornCity;
            TxtBoxDenouncedAddress.Text = aggressor.Address;
            TxtBoxDenouncedZone.Text = aggressor.Zone;
            comboBoxDenouncedMaritalState.Text = aggressor.CivilStatus;
            datePickerBirthDateAggressor.SelectedDate = aggressor.BirthDate;
        }

        void FillEmployee()
        {
            TxtBoxCIPolice.Text = functionary.CI.ToString();
            TxtBoxPoliceName.Text = functionary.Name;
            TxtBoxPolicePName.Text = functionary.PaternalName;
            TxtBoxPoliceMName.Text = functionary.MaternalName;
            TxtBoxPoliceRank.Text = functionary.Rank;
        }

        void FillOfficer()
        {
            TxtBoxCiOffice.Text = official.CI.ToString();
            TxtBoxOfficeName.Text = official.Name;
            TxtBoxOfficePN.Text = official.PaternalName;
            TxtBoxOfficeMN.Text = official.MaternalName;
            comboBoxOfficeRank.Text = official.Rank;
            TxtBoxOfficeDepartament.Text = official.PoliceStation;
            TxtBoxOfficeWorkPlace.Text = official.Place;
            TxtBoxOfficeZone.Text = official.Zone;
        }

        void FillFact()
        {
            TxtBoxFactNature.Text = directAction.IncidentNature;
            rbtnPublicAmbit.IsChecked = complaint.IncidentPlace == "Ambito Publico";
            rbtnPrivateAmbit.IsChecked = complaint.IncidentPlace == "Ambito Privado";
            rbtnZoneCentral.IsChecked = complaint.IncidentZone == "Urbano Central";
            rbtnZonePeriferic.IsChecked = complaint.IncidentZone == "Urbano Periferica";
            rbtnZoneRural.IsChecked = complaint.IncidentZone == "Rural";
            datePickerFactDate.Text = directAction.RegistrationDate.ToShortDateString();
            String time = directAction.IncidentTime.ToString();
            string[] words = time.Split(':');
            String h = words[0];
            String m = words[1];
            cmbBoxHours.SelectedIndex = Convert.ToInt32(h)-1;
            cmbBoxMinutes.SelectedIndex = Convert.ToInt32(m)-1;
            TxtBoxReport.Text = directAction.IncidentReport;
        }

        void getEmployeeEventHandler(object sender, RoutedEventArgs e)
        {
            try
            {
                Employee functionary2 = new Employee();
                functionary2.CI = search.Employee.CI;
                functionary2 = EmployeeDataAccess.GetEmployeeByCi(functionary2.CI);
                search.Close();
                TxtBoxCIPolice.Text = functionary2.CI.ToString();
                TxtBoxPoliceName.Text = functionary2.Name;
                TxtBoxPolicePName.Text = functionary2.PaternalName;
                TxtBoxPoliceMName.Text = functionary2.MaternalName;
                TxtBoxPoliceRank.Text = functionary2.Rank;
               
            }
            catch
            {
                MessageBox.Show("Ocurrio un error al obtener el empleado");
            }

        }

        private bool CheckHasErrors()
        {
            bool res = false;
            foreach (var control in Content.Children)
            {
                GroupBox gp = control as GroupBox;
                if (gp != null)
                {
                    foreach (var ctrl in (gp.Content as Grid).Children)
                    {
                        TextBox tb = ctrl as TextBox;
                        if (tb != null)
                        {
                            tb.GetBindingExpression(TextBox.TextProperty).UpdateSource();
                            if (Validation.GetHasError(tb))
                                res = true;
                        }
                        ValidationComboBox cb = ctrl as ValidationComboBox;
                        if (cb != null)
                        {
                            cb.LostFocusEventHandler(cb, null);
                            if (Validation.GetHasError(cb))
                                res = true;
                        }
                        ValidDatePicker dtp = ctrl as ValidDatePicker;
                        if (dtp != null)
                        {
                            dtp.GetBindingExpression(DatePicker.TextProperty).UpdateSource();
                            dtp.LostFocusEventHandler(dtp, null);
                            if (Validation.GetHasError(dtp))
                                res = true;
                        }
                    }
                }
            }
            
            return res;
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                bool hasErrors = CheckHasErrors();
                if (!hasErrors)
                {
                    if (GetOfficial() && GetComplainant() && GetAggressor())//si todo esta bien
                    {
                        if (GetFact(official.CI, complainant.CiPassport, Convert.ToInt64(TxtBoxCIPolice.Text), aggressor.CiPassport))
                        {
                            if (LastCiEmployee != -1)
                            {
                                long ci = Convert.ToInt64(TxtBoxCiOffice.Text.Trim());
                                //official.CI = ci;
                                InterveningPolice other = new InterveningPolice();                                
                                other.CI = ci;
                                other.Name = TxtBoxOfficeName.Text.Trim();
                                other.PaternalName = TxtBoxOfficePN.Text.Trim();
                                if (String.IsNullOrEmpty(TxtBoxOfficeMN.Text))
                                    other.MaternalName = TxtBoxOfficeMN.Text.Trim();
                                other.PoliceStation = TxtBoxOfficeDepartament.Text.Trim();
                                other.Place = TxtBoxOfficeWorkPlace.Text.Trim();
                                other.Zone = TxtBoxOfficeZone.Text.Trim();
                                if (!DataAccess.InterveningPoliceDataAccess.PoliceAlreadyExists(Convert.ToInt64(other.CI)))
                                    other = DataAccess.InterveningPoliceDataAccess.InsertInterveningPolice(other);
                                else
                                    MessageBox.Show("El CI del policia interviniente ya existe, le pertenece a otra persona seleccione otro");
                                directAction.CIInterveningPolice = ci;
                            }
                            
                            ManageDirectAction();
                            ManageOffice();
                            bool rc = registerComplaint();
                            ManageAggressor();
                            ManageComplainant();
                            if (rc)
                            {
                                MessageBoxResult result = Xceed.Wpf.Toolkit.MessageBox.Show("Reporte de Accion Directa modificado! Desea imprimirlo?", "Information", MessageBoxButton.YesNo, MessageBoxImage.Question);
                                if (result == MessageBoxResult.Yes)
                                {
                                    var items = new ObservableCollection<UserControl>();
                                    items.Add(new PrintDirectAction(complaint.Id));
                                    items.Add(new PrintDirectionActionPart2(complaint.Id));
                                    var a = new PrintPreviewDialogV2(items);
                                    a.ShowDialog();
                                }
                                else
                                {
                                    Xceed.Wpf.Toolkit.MessageBox.Show("Puede imprimir la accion directa posteriormente, entrando a Ver Denuncias, click sobre la denuncia selecciona la opción Ver Accion Directa",
                                                               "Información!", MessageBoxButton.OK, MessageBoxImage.Information);
                                }
                                UIWindowManager.CleanWindow(this);
                            }
                            else
                            {
                                Xceed.Wpf.Toolkit.MessageBox.Show("Error en el servidor Intente modificar los datos mas tarde", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                                UIWindowManager.CleanWindow(this);
                            }
                        }

                    }
                }
                else
                {
                    Xceed.Wpf.Toolkit.MessageBox.Show("Todos los campos deben ser llenados", "Aviso", MessageBoxButton.OK,
                                    MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("Errores al insertar Accion directa", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        

        private void ManageComplainant()
        {
                complainant = PersonAndActorDataAccess.UpdatePerson(complainant.CiPassport,complainant);
                if (complainant == null)
                {
                    MessageBox.Show("Error al modificar denunciante");
                }
               
        }

        private void ManageAggressor()
        {
                aggressor = PersonAndActorDataAccess.UpdatePerson(aggressor.CiPassport,aggressor);
                if (aggressor == null)
                {
                    MessageBox.Show("Error al modificar agresor");
                }
        }

        private void ManageOffice()
        {
            if(LastCiEmployee!=-1)
                DataAccess.InterveningPoliceDataAccess.DeleteInterveningPolice(LastCiEmployee);
            else
                DataAccess.InterveningPoliceDataAccess.UpdateInterveningPolice(official.CI, official);
        }

        private void ManageDirectAction()
        {
            directAction = DirectActionDataAccess.UpdateDirectAction(directAction.Id, directAction);
            if (directAction == null)
                MessageBox.Show("Error al modificar datos de accion directa", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private void setRulesOffice()
        {
            //policia interviniente
            TxtBoxOfficeName.AddValitationRule(new ShortStringRule(3));
            TxtBoxOfficePN.AddValitationRule(new ShortStringRule(3));

            TxtBoxOfficeMN.DeactivateBlankValidation();
            TxtBoxOfficeDepartament.AddValitationRule(new ShortStringRule(3));
            TxtBoxCIPolice.AddValitationRule(new ShortStringRule(4));

            TxtBoxOfficeZone.AddValitationRule(new ShortStringRule(3));
            TxtBoxOfficeWorkPlace.AddValitationRule(new ShortStringRule(2));
        }

        private void setRulesFact()
        {
            TxtBoxFactNature.AddValitationRule(new ShortStringRule(3));
            TxtBoxReport.AddValitationRule(new ShortStringRule(10));
        }

        private void setRulesDenounced()
        {
            //denunciado
            TxtBoxDenouncedName.AddValitationRule(new ShortStringRule(3));
            TxtBoxDenouncedPN.AddValitationRule(new ShortStringRule(3));
            TxtBoxDenouncedMN.DeactivateBlankValidation();
            TxtBoxDenouncedCi.AddValitationRule(new ShortStringRule(5));
            TxtBoxDenouncedOccupation.AddValitationRule(new ShortStringRule(3));
            TxtBoxDenouncedAddress.AddValitationRule(new ShortStringRule(3));
            TxtBoxDenouncedPhone.DeactivateBlankValidation();
            TxtBoxDenouncedPhone.DeactivateBlankValidation();
            TxtBoxDenouncedBornPlace.AddValitationRule(new ShortStringRule(3));
            TxtBoxDenouncedZone.AddValitationRule(new ShortStringRule(3));
        }

        private void setRulesComplainant()
        {
            //denunciante
            TxtBoxComplainantName.AddValitationRule(new ShortStringRule(3));
            TxtBoxComplainantPN.AddValitationRule(new ShortStringRule(3));
            TxtBoxComplainantMN.DeactivateBlankValidation();
            TxtBoxCiComplainant.AddValitationRule(new ShortStringRule(5));
            TxtBoxComplainantOccupation.AddValitationRule(new ShortStringRule(3));
            TxtBoxComplainantAddress.AddValitationRule(new ShortStringRule(3));
            TxtBoxComplainantPhone.DeactivateBlankValidation();
            TxtBoxComplainantZone.AddValitationRule(new ShortStringRule(3));
            TxtBoxComplainantBornPlace.AddValitationRule(new ShortStringRule(3));
        }

        private void setRulesPolice()
        {
            //policia encargada
            TxtBoxPoliceName.AddValitationRule(new ShortStringRule(3));
            TxtBoxPolicePName.AddValitationRule(new ShortStringRule(3));
            TxtBoxPoliceMName.DeactivateBlankValidation();
            TxtBoxCIPolice.AddValitationRule(new ShortStringRule(4));
        }

        private void SetRules()
        {
            setRulesOffice();
            setRulesFact();
            setRulesDenounced();
            setRulesComplainant();
            setRulesPolice();
        }

        private bool GetOfficial()
        {
            try
            {
                official.Name = TxtBoxOfficeName.Text.Trim();
                official.PaternalName = TxtBoxOfficePN.Text.Trim();
                official.MaternalName = TxtBoxOfficeMN.Text.Trim();
                official.PoliceStation = TxtBoxOfficeDepartament.Text.Trim();
                official.Place = TxtBoxOfficeWorkPlace.Text.Trim();
                official.Zone = TxtBoxOfficeZone.Text.Trim();
                return true;
            }
            catch
            {
                MessageBox.Show("error al obtener los datos del hecho");
                return false;
            }
        }

        private bool GetFact(long CIInterveningPolice, long IdComplainant, long CIEmployee, long IdAggressor)
        {
            try
            {
                directAction.CIEmployee = CIEmployee;
                directAction.CIInterveningPolice = CIInterveningPolice;
                directAction.IncidentReport = TxtBoxReport.Text.Trim();
                TimeSpan time = new TimeSpan(Convert.ToInt32(Hours), Convert.ToInt32(Minutes), 0);
                directAction.IncidentTime = time;
                directAction.RegistrationDate = DateTime.Now;
                directAction.IncidentNature = TxtBoxFactNature.Text.Trim();
                directAction.CompleteComplaint = false;
                directAction.Status = true;
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("error al obtener los datos del hecho");
                return false;
            }
        }

        private bool GetComplainant()
        {
            try
            {
                //complainant.Id = TxtBoxCiComplainant.Text + DateTime.Now.Date.ToString(CultureInfo.GetCultureInfo("es-ES").DateTimeFormat.ShortDatePattern);
                complainant.CiPassport = Convert.ToInt64(TxtBoxCiComplainant.Text.Trim());
                complainant.Name = TxtBoxComplainantName.Text.Trim();
                complainant.PaternalName = TxtBoxComplainantPN.Text.Trim();
                complainant.MaternalName = TxtBoxComplainantMN.Text.Trim();
                complainant.BirthDate = datePickerBirthDateCamplainant.DisplayDate;
                complainant.Phone = TxtBoxComplainantPhone.Text;
                complainant.Ocupation = TxtBoxComplainantOccupation.Text.Trim();
                complainant.BornCity = TxtBoxComplainantBornPlace.Text.Trim();
                complainant.Address = TxtBoxComplainantAddress.Text.Trim();
                complainant.Zone = TxtBoxComplainantZone.Text.Trim();
                complainant.RegisterDate = DateTime.Now.Date;
                complainant.Status = true;
                return true;
            }
            catch
            {
                MessageBox.Show("error al obtener los datos del hecho");
                return false;
            }
        }

        private bool GetAggressor()
        {
            try
            {
                //aggressor.Id = TxtBoxDenouncedCi.Text + DateTime.Now.Date.ToString(CultureInfo.GetCultureInfo("es-ES").DateTimeFormat.ShortDatePattern);
                aggressor.Name = TxtBoxDenouncedName.Text.Trim();
                aggressor.PaternalName = TxtBoxDenouncedPN.Text.Trim();
                aggressor.MaternalName = TxtBoxDenouncedMN.Text.Trim();
                aggressor.CiPassport = Convert.ToInt64(TxtBoxDenouncedCi.Text.Trim());
                aggressor.BirthDate = datePickerBirthDateAggressor.DisplayDate;
                aggressor.Phone = TxtBoxDenouncedPhone.Text;
                aggressor.Ocupation = TxtBoxDenouncedOccupation.Text.Trim();
                aggressor.BornCity = TxtBoxDenouncedBornPlace.Text.Trim();
                aggressor.Address = TxtBoxDenouncedAddress.Text.Trim();
                aggressor.Zone = TxtBoxDenouncedZone.Text.Trim();
                return true;
            }
            catch
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("error al obtener los datos del hecho");
                return false;
            }
        }

        private bool registerComplaint()
        {
            try
            {
                complaint.IncidentDate = datePickerFactDate.SelectedDate;
                complaint.IncidentPlace = rbtnPrivateAmbit.IsChecked == true ? "Ambito Privado" : rbtnPublicAmbit.IsChecked == true ? "Ambito Publico" : null;
                complaint.IncidentZone = rbtnZoneCentral.IsChecked == true ? "Urbano Central" : (rbtnZoneRural.IsChecked == true ? "Rural" : rbtnZonePeriferic.IsChecked == true ? "Urbano Periferica" : null);
                complaint.IdDirectAction = directAction.Id;
                complaint = DataAccess.ComplaintDataAccess.UpdateComplaint(complaint.Id,complaint);
                return true;
            }
            catch
            {
                Xceed.Wpf.Toolkit.MessageBox.Show("error al registrar");
                return false;
            }
        }

        private void comboBoxComplainantMaritalStatus_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBoxComplainantMaritalStatus.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)comboBoxComplainantMaritalStatus.SelectedValue;
                complainant.CivilStatus = item.Content.ToString();
            }
        }

        private void comboBoxDenouncedMaritalState_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBoxDenouncedMaritalState.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)comboBoxDenouncedMaritalState.SelectedValue;
                aggressor.CivilStatus = item.Content.ToString();
            }
        }

        private void cmbBoxHours_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbBoxHours.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)cmbBoxHours.SelectedValue;
                Hours = item.Content.ToString();
            }
        }

        private void cmbBoxMinutes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbBoxMinutes.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)cmbBoxMinutes.SelectedValue;
                Minutes = item.Content.ToString();
            }
        }

        private void comboBoxOfficeRank_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBoxOfficeRank.SelectedIndex != -1)
            {
                ComboBoxItem item = (ComboBoxItem)comboBoxOfficeRank.SelectedValue;
                official.Rank = item.Content.ToString();
            }
        }

        private void TxtBoxCIPolice_GotFocus(object sender, RoutedEventArgs e)
        {
            search = new SearchFunctionary();
            search.getEmployee += new RoutedEventHandler(getEmployeeEventHandler);
            search.ShowDialog();
            TxtBoxCIPolice.Focusable = false;
        }

        private void TxtBoxPoliceName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxCIPolice_GotFocus(sender, e);
            TxtBoxPoliceName.Focusable = false;
        }

        private void TxtBoxPolicePName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxCIPolice_GotFocus(sender, e);
            TxtBoxPolicePName.Focusable = false;
        }

        private void TxtBoxPoliceMName_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxCIPolice_GotFocus(sender, e);
            TxtBoxPoliceMName.Focusable = false;
        }

        private void TxtBoxPoliceRank_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtBoxCIPolice_GotFocus(sender, e);
            TxtBoxPoliceRank.Focusable = false;
        }

        private void btnKeyComplainant_Click(object sender, RoutedEventArgs e)
        {
            Director = new GrantDirectorPermissionWindows();
            bool result = Convert.ToBoolean(Director.ShowDialog());
            if (result)
            {
                TxtBoxCiOffice.IsEnabled = true;
                LastCiEmployee = official.CI;
            }
            else
                MessageBox.Show("Datos incorrectos", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {

        }
    }
}
